<template>
  <div class="app-container">
    <!-- <div class="filter-container">
      <el-input v-model="listQuery.username" placeholder="用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div> -->

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.gmtDatetime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.state==1" type="success">
            启用
          </el-tag>
          <el-tag v-if="row.state==0" type="danger">
            停用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="300px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑权限
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getRoles"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="adminDto" label-position="left" label-width="90px" style=" margin-left:50px;">
        <el-form-item label="菜单">
          <el-tree
            ref="tree"
            :data="routes"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[2, 3]"
            :default-checked-keys="checkedRoute"
            :check-strictly="true"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, allMenus, updateRoute } from '@/api/role'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'RolePermission',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      routes: [],
      roleId: -1,
      checkedRoute: [],
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 10,
        importance: undefined,
        username: undefined,
        sort: '+id'
      },
      adminDto: {
        id: undefined,
        gmtDatetime: new Date(),
        username: '',
        state: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        username: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      listLoading: false
    }
  },
  created() {
    this.getRoles(null)
  },
  methods: {
    async updateData() {
      var ids = ''
      const pers = this.$refs.tree.getCheckedNodes()
      for (let index = 0; index < pers.length; index++) {
        const element = pers[index]
        if (pers.length === index + 1) {
          ids += element.id
        } else {
          ids += element.id
          ids += ','
        }
      }
      const res = await updateRoute({ persId: ids, roleId: this.roleId })
      if (res.data.code === 200) {
        this.$notify({
          title: '更新成功！',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
        this.dialogFormVisible = false
        this.routes = []
        this.checkedRoute = []
      } else {
        this.$notify({
          title: '更新失败！',
          message: '更新失败',
          type: 'fail',
          duration: 2000
        })
        this.dialogFormVisible = false
        this.routes = []
        this.checkedRoute = []
      }
    },
    // 获取列表
    async getRoles(listQuery) {
      const res = await getRoles(listQuery)
      this.tableData = res.data.data.data
      this.total = res.data.data.count
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getRoles(this.listQuery)
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    generateArr(routes) {
      var that = this
      routes.forEach(route => {
        if (route.selected) {
          that.checkedRoute.push(route.id)
          if (route.children.length !== 0) {
            this.generateArr(route.children)
          }
        }
      })
    },
    async handleUpdate(row) {
      this.roleId = row.id
      const res = await allMenus({ roleId: this.roleId })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.routes = res.data.data
      this.generateArr(this.routes)
      this.$nextTick(() => {
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false
        this.$refs['dataForm'].clearValidate()
      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
